package com.mintyfresh.tns.util;

/**
 * This class contains some methods for chosing parent
 * names of categorical data (a.b.c).
 */
public class Hierarchy {
    /** removes the suffix of a name, and replaces it with
     * a glob match.
     *
     * <pre>
     * "abc.xyz/q" --&gt; "abc.xyz/*"
     * "abc.xyz/*" --&gt; "abc.xyz*"
     * "abc.xyz*"  --&gt; "abc.*"
     * "abc.*"     --&gt; "abc*"
     * "abc*"      --&gt; "*" * // skip "abc", "abc" doesn't match "abc.*"
     * "*"         --&gt; null
     * </pre>
     */
    public static String parentName(String name) {
        // X.* --> X*
        // X/* --> X*
        if(name.endsWith(".*") || name.endsWith("/*")) { 
            return name.substring(0, name.length()-2) + "*";
        // X --> X*
        } else if(!name.endsWith("*")) {
            return name + "*";
            // * --> null
        } else if(name.equals("*")) {
            name = null;
        } else {

            // X.Y* --> X.*
            // X/Y* --> X/*
            // X* ----> *
            int lastDot = name.lastIndexOf('.');
            int lastSlash = name.lastIndexOf('/');
            int lastDotSlash = Math.max(lastDot, lastSlash);

            if(lastDotSlash != -1) {
                name = name.substring(0, lastDotSlash + 1) + "*";
            } else {
                name = "*";
            }
        }

        return name;
    }

    /** checks if the child has a parent in the form of <tt>parent</tt>,
     * on the standard hierarchy.
     */
    public static boolean childOf(String child, String parent) {
        // if the parent is a "match all", make it so now:
        if(parent.equals("*"))
            return true;

        if(child == null)
            return false;

        if(child.equals(parent))
            return true;

        // if the parent isn't a glob,
        // the child will be a glob next iteration,
        // so just return false now.
        if(!parent.endsWith("*"))
            return false;

        return childOf(parentName(child), parent);
    }
}
